<template>
  <div class="registerInfo-container">
    <modules-title title-name="全盘盘点">
      <template slot="btn">
        <el-button type="primary" class="main-btn" @click="toIndex">盘点日志</el-button>
        <el-button type="primary" class="main-btn" @click="save">保存</el-button>
      </template>
    </modules-title>
    <div class="main">
      <div class="table">
        <el-form :model="formData" ref="formData" :rules="rules" class="demo-ruleForm">
          <el-table
            :data="formData.tableData"
            :header-cell-style="{
                        backgroundColor: '#F5F5F5',
                        color: '#333333',
                        fontFamily: 'MicrosoftYaHeiUI',
                        fontSize: '14px',
                        fontWeight: 900,
                    }"
          >
            <el-table-column type="index">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  {{scope.$index + 1}}
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="药品名称"  width="200">
              <template slot-scope="scope">
                <el-form-item class="item_form"
                              :prop="'tableData.'+scope.$index+'.product_name'"
                              :rules="rules.tableDataP_name"
                >
                  <el-autocomplete
                    class="table_input_n"
                    v-model="scope.row.product_name"
                    :fetch-suggestions="querySearch"
                    placeholder="药品关键字"
                    :trigger-on-focus="false"
                    :popper-append-to-body="false"
                    @focus="focusInp(scope.$index)"
                    @change="(item)=>{onChangeInp(scope.$index,item)}"
                    @clear="clearSl(scope.$index)"
                    @select="(item)=>{handleSelect(scope.$index,item)}">
                    <template slot-scope="{ item }">
                      <div class="product-item">
                        <div class="name">
                          <span>{{ item.product_name }}</span
                          ><span>({{ item.pack }})</span>
                          <span>({{ item.production }})</span>
                        </div>
                      </div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="规格" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  {{scope.row.pack}}
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="厂家" width="280" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  {{scope.row.production}}
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="批准文号" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  {{scope.row.approval}}
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="批号" v-if="state.drugs_management.function_set" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  <el-select v-model="scope.row.batch_no"
                             placeholder=""
                             @change="onchangeBo(scope.$index,scope.row.batch_no)" class="table_input_p">
                    <el-option
                      v-for="item in scope.row.list"
                      :key="item.store_id"
                      :label="item.batch_no"
                      :value="item">
                    </el-option>
                  </el-select>

                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="库存" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  {{scope.row.number}}{{scope.row.unit}}
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="230">
              <template slot="header" slot-scope="scope">
                <span style="color: red">*</span><span>数量(盘点库存)</span>
              </template>
              <template slot-scope="scope">
                <el-form-item class="item_form"
                              :prop="'tableData.'+scope.$index+'.check_number'"
                              :rules="rules.tableDataN"
                >
                  <div class="el-table_big">
                    <div class="el-table_box">
                      <el-input v-model.number="scope.row.check_number" @blur="blurNn(scope.$index)"
                                :ref="'numIn' + scope.$index"
                                class="table_input1">
                      </el-input>
                      <el-select v-model="scope.row.unit" @change="onChangeUn(scope.$index,scope.row.unit)"
                                 class="table_select1" placeholder="">
                        <el-option
                          v-for="item in scope.row.unitList"
                          :key="item"
                          :label="item"
                          :value="item">
                        </el-option>
                      </el-select>
                    </div>
                    <i class="el-icon-delete delete" @click="deleteDrug(scope.$index)"></i>
                  </div>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div>
          <el-button @click="addDrug" type="text">添加药品</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      class="dialog"
      title="系统提示"
      :visible.sync="dialogVisible"
      width="24%"
      :close-on-click-modal="false">
      <div class="div_title">是否确定保存?</div>
      <span slot="footer" class="dialog-footer">
          <el-button class="border-btn" @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" class="main-btn" :disabled="booleBu" @click="determine">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    getOutStorageList,
    getCentralList,
    addInventory,
    getOutCentralList,
    getOutDefault
  } from '@/api/drugsManagement';

  export default {
    name: 'allInventory',
    data() {
      var checkSe = (rule, value, callback) => {
        let that = this
        if (value === '' || value === null) {
          callback(new Error('请输入数量'));
        } else if (that.inputList.length === 0) {
          callback(new Error('该药品没有被录入'));
        } else {
          callback();
        }
      };
      var checkNu = (rule, value, callback) => {
        var reg = /(^[0-9]\d*$)/
        if (value === '' || value === null) {
          callback(new Error('请输入数量'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入正确数量'));
        } else if (value > 999999) {
          callback(new Error('入库数量最大值9999'));
        } else {
          callback();
        }
      };
      return {
        dialogVisible: false,
        formData: {
          tableData: [
            {
              product_name: '',
              pack: '药品规格',
              production: '厂家',
              product_id: 0,
              batch_no: '',//批次号
              number: 0,//出库数量
              check_number: '',
              number_unit: '',
              approval: '批准文号',
              id: 0,
              unitList: [],
              unit: '',

            }
          ],
        },
        drugList: [],
        defaultList: [],
        count: 0,
        rules: {
          tableDataP_name: [{validator: checkSe, trigger: 'blur',}],
          tableDataN: [{validator: checkNu, trigger: 'blur'}],
        },
        state: {},
        booleBu: false,
        booleP_n: false,
        inputList: [],
        index: 0
      }
    },
    watch: {
      formData: {
        handler() {
          if (this.formData.tableData.length > 0) {
            for (var i = 0; i < this.formData.tableData.length; i++) {
              if (this.formData.tableData[i].product_id > 0) {
                this.count++
              }
            }
          } else {
            this.count = 0
          }


        },
        deep: true
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.count > 1) {
        this.$confirm('有内容未保存, 是否确定离开此页面?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          next()
        }).catch(() => {
          next(false)
        });
      } else {
        next()
      }
    },
    created() {
      this.state = JSON.parse(this.$store.getters.systemSetting.dic_value)
    },
    methods: {
      getCentralListData(data) {
        getCentralList(data).then(res => {
          if (res.code === 200) {
            if (res.data.self === true) {
              this.drugList = res.data.ElasticProduct
            }
          } else {
            this.drugList = []
          }
        })
      },
      async querySearch(queryString, cb) {
        let reg = /^[a-zA-Z]+$/.test(queryString)
        if (reg === true) {
          queryString = queryString.toLowerCase()
        }

        let res = await getCentralList({prefix: queryString.replace(/(^\s*)|(\s*$)/g, ""), size: 10})
        if (res.code === 200 && res.data.self === true) {
          this.inputList = res.data.ElasticProduct || []
        } else {
          this.inputList = []
          this.formData.tableData[this.index].product_name = queryString
          this.product_name = queryString
          this.booleP_n = true

        }
        console.log(this.formData.tableData, "--=-=-")
        var results = this.inputList;
        cb(results);
      },
      handleSelect(index, val) {
        this.formData.tableData[index].id = val.id
        getOutDefault(val.id).then(res => {
          if (res.code === 200 && res.data !== null) {
            this.defaultList = res.data.data
            if (this.defaultList !== null) {
              this.formData.tableData[index].product_name = this.defaultList.product_name//名称
              this.formData.tableData[index].pack = this.defaultList.pack//规格
              this.formData.tableData[index].production = this.defaultList.production//厂家
              this.formData.tableData[index].approval = this.defaultList.approval//批准文号
              this.formData.tableData[index].list = this.defaultList.list
              this.formData.tableData[index].unit = this.defaultList.number_unit || this.defaultList.piece_unit
              this.formData.tableData[index].product_id = this.defaultList.id//
              if (this.defaultList.number_unit === '') {
                this.formData.tableData[index].unitList = [this.defaultList.piece_unit]
              } else {
                this.formData.tableData[index].unitList = [this.defaultList.number_unit]
                if (this.defaultList.number_unit !== this.defaultList.piece_unit) {
                  this.formData.tableData[index].unitList.push(this.defaultList.piece_unit)
                }
              }
              this.formData.tableData[index].number = this.defaultList.list[0].number//库存
              this.formData.tableData[index].batch_no = this.defaultList.list[0].batch_no//批号
              if (this.state.drugs_management.function_set === false) {
                this.formData.tableData[index].number = this.defaultList.list[0].number//库存
                this.formData.tableData[index].batch_no = this.defaultList.list[0].batch_no//批号
              }
            }
          }
        })

      },
      onChangeInp(index, val) {
        this.formData.tableData[index].product_name = val
        console.log(val, "544544")
        if (val === '') {
          this.clearSl(index)
        }
      },

      onChangeUn(index, val) {
        this.formData.tableData[index].unit = val
      },
      //批号选择事件
      onchangeBo(index, val) {
        this.formData.tableData[index].number = val.number//库存
        this.formData.tableData[index].batch_no = val.batch_no//批号
        this.formData.tableData[index].product_id = val.store_id//
      },
      //select获取焦点添加
      focusInp(index) {
        this.index = index
        this.inputList = []
        if (index === this.formData.tableData.length - 1) {
          this.addDrug()
        }
      },
      //select失去焦点
      blurIn(index) {
        if (this.inputList.length === 0 && this.formData.tableData[index].product_name === this.product_name) {
          this.formData.tableData[index].product_id = -1
        }
      },
      //select清除
      clearSl(index) {
        this.inputList = []
        this.count--
        this.formData.tableData[index].product_name = ''
        this.formData.tableData[index].pack = '药品规格'
        this.formData.tableData[index].production = '厂家'
        this.formData.tableData[index].numberr = 0
        this.formData.tableData[index].product_id = 0
        this.formData.tableData[index].id = 0
        this.formData.tableData[index].approval = '批准文号'
        this.formData.tableData[index].batch_no = ''//批次号
        this.formData.tableData[index].check_number = ''//出库数量

      },
      //数量焦点事件
      blurNn(index) {
        this.index = index
        var reg = /(^[1-9]\d*$)/
        if (!this.formData.tableData[index].check_number || this.formData.tableData[index].check_number === '') {
        } else {
          if (!reg.test(this.formData.tableData[index].check_number)) {
            this.formData.tableData[index].check_number = ''
          } else {
            if (Number(this.formData.tableData[index].check_number) > 999999) {
              this.formData.tableData[index].check_number = ''
            }
          }
        }

      },
      //保存
      save() {
        for (var i = 0; i < this.formData.tableData.length; i++) {
          if (this.formData.tableData[i].product_name.split(" ").join("").length !== 0) {
            if (this.formData.tableData[i].product_name !== '' || this.formData.tableData[i].product_name !== null) {
              this.$confirm('是否确定保存？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(_ => {
                this.determine()
              }).catch(_ => {
              })
            }
          }
        }
      },
      //保存确定
      determine() {
        var arr = [], data = [], boole = true, boolList = false;
        for (var i = 0; i < this.formData.tableData.length; i++) {
          if (this.formData.tableData[i].product_name.split(" ").join("").length !== 0) {
            if (this.formData.tableData[i].product_name !== '' || this.formData.tableData[i].product_name !== null) {
              if (this.formData.tableData[i].check_number === '' || this.formData.tableData[i].check_number === null) {
                let str = "numIn" + i
                this.$nextTick(_ => {
                  this.$refs[str].focus()
                  this.$refs[str].blur()
                })
                boole = false
              } else {
                if (this.formData.tableData[i].product_id > 0) {
                  arr.push(i)
                  boolList = true
                }
              }
            }
          }
        }
        console.log(11)
        console.log(this.formData.tableData)
        if (boole && boolList) {
          arr.forEach(item => {
            data.push(
              {
                store_id: this.formData.tableData[item].product_id,
                check_number: Number(this.formData.tableData[item].check_number),
                unit: this.formData.tableData[item].unit
              }
            )
          })
          this.booleBu = true
          addInventory({data}).then(res => {
            console.log(22)
            if (res.code === 200) {
              this.count = 0
              this.$router.push('/drugsManagement/Inventory/index')
            } else {
              this.booleBu = false
            }
          })
        }
      },
      //盘点日志
      toIndex() {
        this.$router.push('/drugsManagement/Inventory/index')
      },
      //添加药品
      addDrug() {
        this.formData.tableData.push(
          {
            product_name: '',
            pack: '药品规格',
            production: '厂家',
            product_id: 0,
            batch_no: '',//批次号
            number: 0,//出库数量
            number_unit: '',
            check_number: '',
            approval: '批准文号',
            id: 0,
            unitList: [],
            unit: '',
          }
        )
      },
      //删除药品
      deleteDrug(index) {
        for (let i = 0; i < this.formData.tableData.length; i++) {
          if (i === index) {
            this.$refs.formData.fields.map(j => {
              let str = `tableData.${i}.check_number`
              let er = `tableData.${i}.product_name`
              if (j.prop === str) {
                j.clearValidate()
              } else if (j.prop === er) {
                j.clearValidate()
              }
            })
            this.formData.tableData.splice(i, 1)
          }
        }

      }
    }
  }
</script>
<style lang="scss" scoped>
  @import "@/assets/scss/drugsManagement/allInventory.scss";

  ::v-deep .el-autocomplete-suggestion {
    width: auto !important;
  }

  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: rgba(0, 0, 0, 0) !important;
  }
</style>

